package com.snail.billing.util;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.android.os.MyEngine;

public class BillingUtil {

	public static boolean isNetworkAvailable() {
		ConnectivityManager connManager = (ConnectivityManager) MyEngine.getEngine().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
			return true;
		}
		return false;
	}

	public static String getLocalIp() {
		Enumeration<NetworkInterface> netInterfaces = null;
		try {
			StringBuffer result = new StringBuffer();
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = netInterfaces.nextElement();
				if (ni.isLoopback() || ni.isVirtual() || !ni.isUp())
					continue;
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				while (ips.hasMoreElements()) {
					InetAddress ia = ips.nextElement();
					if (ia instanceof Inet6Address)
						continue;
					result.append(ia.getHostAddress()).append(",");
				}
			}
			return result.toString().substring(0, result.length() - 1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String getAppVersion() {
		Context context = MyEngine.getEngine().getApplicationContext();
		try {
			return context.getPackageManager().getPackageInfo(context.getPackageName(), Context.MODE_PRIVATE).versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 获取手机的IMEI值，为手机的唯一标示符。
	 * 
	 * @return 手机的IMEI值。
	 */
	public static String getIMEICode() {
		Context context = MyEngine.getEngine().getApplicationContext();
		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		return telephonyManager.getDeviceId();
	}
	
	/**
	 * 获取手机运营商信息。
	 */
	public static String getProviderName() {
		Context context = MyEngine.getEngine().getApplicationContext();
		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String providerId = telephonyManager.getSubscriberId();
		if (!TextUtils.isEmpty(providerId)) {
			if (providerId.startsWith("46000") || providerId.startsWith("46002")) {
				// return "中国移动";
				return "2";
			} else if (providerId.startsWith("46001")) {
				// return "中国联通";
				return "1";
			} else if (providerId.startsWith("46003")) {
				// return "中国电信";
				return "3";
			}
		}
		return "";
	}

}
